package org.feng.lifecycle;

import io.quarkus.security.identity.AuthenticationRequestContext;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.SecurityIdentityAugmentor;
import io.quarkus.security.runtime.QuarkusSecurityIdentity;
import io.smallrye.mutiny.Uni;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

import org.feng.entity.User;
import org.hibernate.FlushMode;

import java.util.List;
import java.util.function.Supplier;

@ApplicationScoped
public class keyChuanIdentityAugmentor implements SecurityIdentityAugmentor {
	
	//@PersistenceUnit("users") 
    @Inject
    EntityManagerFactory entityManagerFactory;


	@Override
	public Uni<SecurityIdentity> augment(SecurityIdentity identity, AuthenticationRequestContext context) {
		return Uni.createFrom().item(build(identity));

		// Do 'return context.runBlocking(build(identity));'
		// if a blocking call is required to customize the identity
	}

	private Supplier<SecurityIdentity> build(SecurityIdentity identity) {
		if (identity.isAnonymous()) {
			return () -> identity;
			
		} else {
			// create a new builder and copy principal, attributes, credentials and roles
			// from the original identity
			QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder(identity);
			
			//把用户信息放入验证信息,在别处使用
			//entityManagerFactory.
			EntityManager em = entityManagerFactory.createEntityManager();
            ((org.hibernate.Session) em).setHibernateFlushMode(FlushMode.MANUAL);
            ((org.hibernate.Session) em).setDefaultReadOnly(true);
            Query query = em.createQuery("from User where tel ='"+identity.getPrincipal().getName()+"'");
            User user = (User)query.getResultList().get(0);
			//User u=em.find(User.class, "userName",identity.getPrincipal().getName()).firstResult();
            builder.addAttribute("userInfo",user);
            em.close();
			//builder.addAttribute("userInfo",User.find("userName",identity.getPrincipal().getName()).firstResult());
            
			return builder::build;
		}
	}
}